import store from "../store";
import {ring} from "../utils/ring";

let Socket = null;
let webSocketUrl = 'ws://10.181.255.203:8888/chat';
let lockReconnect = false;
let timeInterval;

let initSocket = () => {
    if ('WebSocket' in window) {
        Socket = new WebSocket(webSocketUrl);
    } else {
        console.error('请检查浏览器是否支持websocket！');
    }
    //连接成功
    Socket.onopen = function () {
        console.log('websocket连接成功！');
        //向WebSocket服务器发送userId
        Socket.send(JSON.stringify({
            type: "online",
            body:
                {
                    userId: sessionStorage.getItem('ms_psd')
                }
        }));
        console.log("向服务器发送上线消息，userId：", sessionStorage.getItem('ms_psd'))
        heartCheck.startLoop();
    };

    //连接关闭
    Socket.onclose = function (e) {
        console.log('websocket连接关闭！' + e.code + ' ' + e.reason + ' ' + e.wasClean)
        Reconnect();
    };

    //连接出错
    Socket.onerror = function (e) {
        console.error('websocket连接失败！');
        Reconnect();
    };

    Socket.onmessage = function (e) {
        const data = JSON.parse(e.data)
        console.log("websocket收到消息:", data)
        if (data.type === 'chat') {
            ring();
            store.commit('RECEIVE_MESSAGE', data.body);
        }
        heartCheck.reset();
    }
}

let Reconnect = () => {
    if (lockReconnect) {
        return;
    }
    console.log("websocket正在重连");
    lockReconnect = true;
    timeInterval && clearTimeout(timeInterval);
    timeInterval = setTimeout(function () {
        initSocket();
        lockReconnect = false;
    }, 4000)
}

let heartCheck = {
    timeout: 60000,
    timoutObj: null,
    //重置倒计时
    reset: function () {
        console.log("心跳重置")
        clearTimeout(this.timeoutObj);
        this.startLoop();
    },
    startLoop: function () {
        let self = this
        this.timeoutObj = setTimeout(function () {
            try {
                Socket.send(JSON.stringify({
                    type: "ping",
                    body: {
                        userId: sessionStorage.getItem('ms_psd')
                    }
                }));
                self.reset();
            } catch (e) {
                console.log("检测到异常", e)
                Reconnect();
            }
        }, this.timeout)
    }

}

window.onbeforeunload = function () {
    //向WebSocket服务器发送userId
    Socket.send(JSON.stringify({
        type: "offline",
        body:
            {
                userId: sessionStorage.getItem('ms_psd')
            }
    }));
    console.log("向服务器发送下线消息，userId",)
    Socket.close();
}

let Send = (data) => {
    console.log("websocket发送");
    try {
        Socket.send(data);
    } catch (e) {
        console.log("发消息失败：", e)
        Reconnect();
    }
}

initSocket();

export {
    Send
}
